package com.zs.main.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * Copyright 2020 ZS Network Co., Ltd. All rights reserved.
 * 本文件仅限于正数网络技术有限公司内部传阅，禁止外泄以及用于其他的商业目的。
 *
 * @Author quanming
 * @Date 2021/12/14 10:49
 * @Desc
 */
public abstract class AbstractInitializingConfig implements ApplicationContextAware {

    protected ApplicationContext applicationContext;

    protected <T extends Annotation> String handleRequestMapping(String prefixPath, Method method, Class<T> annotationClass) {
        T annotation = method.getAnnotation(annotationClass);
        if (Objects.nonNull(annotation)) {
            String uri;
            PostMapping postMappingAno = method.getAnnotation(PostMapping.class);
            GetMapping getMappingAno = method.getAnnotation(GetMapping.class);
            RequestMapping requestMappingMethodAno = method.getAnnotation(RequestMapping.class);
            if (null != postMappingAno) {
                String postMapping = this.getRequestMapping(postMappingAno.value());
                uri = prefixPath + postMapping;
            } else if (null != getMappingAno) {
                String getMapping = this.getRequestMapping(getMappingAno.value());
                uri = prefixPath + getMapping;
            } else {
                String requestMapping = this.getRequestMapping(requestMappingMethodAno.value());
                uri = prefixPath + requestMapping;
            }
            String requestMapping = uri.replaceAll("//", "/");
            boolean flag = StringUtils.equals("/", StringUtils.substring(requestMapping, requestMapping.length() - 1, requestMapping.length()));
            if (flag) {
                requestMapping = requestMapping.substring(0, requestMapping.length() - 1);
            }
            return requestMapping;
        }
        return null;
    }

    protected String getRequestMapping(String[] value) {
        String postMapping = value[0];
        if (!postMapping.startsWith("/")) {
            postMapping = "/" + postMapping;
        }
        return postMapping;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
